﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using SverigesRadio.SverigesRadioApp.WindowsPhoneApplication.Contracts;

namespace SverigesRadio.SverigesRadioApp.WindowsPhoneApplication
{
    public class NavigationService : INavigationService
    {
        private IDictionary<ViewType, string> viewTypes;
        private PhoneApplicationFrame root;

        public event EventHandler<NavigatedEventHandler> Navigated;

        public static void SendOnNavigatedToMessage(ViewType type)
        {
            GalaSoft.MvvmLight.Messaging.Messenger.Default.Send(ViewType.Programs);
        }

        public NavigationService()
        {

            viewTypes = new Dictionary<ViewType, string>
                            {
                                {ViewType.MainPage, "/MainPage.xaml"},
                                {ViewType.Player, "/Views/Player.xaml"},
                                {ViewType.Programs, "/Views/Programs.xaml"},
                                {ViewType.ProgramInformation, "/Views/ProgramInformation.xaml"}

                            };



        }

        public PhoneApplicationFrame Root
        {
            get
            {
                if (root == null)
                {
                    root = Application.Current.RootVisual as PhoneApplicationFrame;
                    root.Navigated += Root_Navigated;

                }

                return root;
            }
        }

        public void NavigateTo(ViewType view)
        {
            NavigateTo(view, "");
        }

        public void NavigateTo(ViewType view, string queryString)
        {
            var uri = new Uri(string.Format("{0}?{1}&tick={2}", viewTypes[view], queryString, DateTime.Now.Ticks), UriKind.Relative);

            Root.Navigate(uri);
        }

        public void NavigateTo(ViewType view, params string[] queryStrings)
        {
            string queryString = string.Join("&", queryStrings);

            NavigateTo(view, queryString);
        }

        void Root_Navigated(object sender, NavigationEventArgs e)
        {
            if (Navigated != null)
            {
                var viewType = ViewType.Unknown;
                var filePath = e.Uri.ToString().Split('?')[0];

                if(viewTypes.Where(p => p.Value == filePath).Count() > 0)
                    viewType = viewTypes.Where(p => p.Value == filePath).Select(p => p.Key).Single();

                IDictionary<string, string> queryString = ((PhoneApplicationPage) e.Content).NavigationContext.QueryString;

                Navigated(sender, new NavigatedEventHandler(viewType, queryString));
            }
        }
    }


    public enum ViewType
    {
        Unknown,
        Player,
        MainPage,
        Programs,
        ProgramInformation
    }
}
